﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GodPl.Utilities
{
    public static class RandomExtensions
    {
        public static int NextWeightedIndex(this Random rnd, IEnumerable<float> weights)
        {
            var dWeights = weights.Select(x => (double)x);

                //weights.Cast<double>();

            int count = dWeights.Count();
            double totalWeight = dWeights.Sum();

            double randVal = rnd.NextDouble() * totalWeight;

            int selectedIndex = -1;

            for(int i = 0; i < count; ++i)
            {
                if (randVal < dWeights.ElementAt(i))
                {
                    selectedIndex = i;
                    break;
                }

                randVal -= dWeights.ElementAt(i);
            }

            return selectedIndex;
        }
    }
}
